package com.xjrsoft.module.erpModel.caseErpSale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.module.erpModel.caseErpCustomer.entity.CaseErpCustomer;
import com.xjrsoft.module.erpModel.caseErpCustomer.service.ICaseErpCustomerService;
import com.xjrsoft.module.erpModel.caseErpLog.entity.CaseErpLog;
import com.xjrsoft.module.erpModel.caseErpLog.service.ICaseErpLogService;
import com.xjrsoft.module.erpModel.caseErpSale.dto.CaseErpSalePageDto;
import com.xjrsoft.module.erpModel.caseErpSale.entity.CaseErpSale;
import com.xjrsoft.module.erpModel.caseErpSale.entity.CaseErpSaleDetail;
import com.xjrsoft.module.erpModel.caseErpSale.mapper.CaseErpSaleMapper;
import com.xjrsoft.module.erpModel.caseErpSale.service.ICaseErpSaleDetailService;
import com.xjrsoft.module.erpModel.caseErpSale.service.ICaseErpSaleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.module.erpModel.caseErpSale.utils.DataBuildUtil;
import com.xjrsoft.module.erpModel.caseErpSale.vo.CaseErpSaleCheckInfoVo;
import com.xjrsoft.module.erpModel.caseErpSale.vo.CaseErpSalePageVo;
import com.xjrsoft.module.erpModel.caseErpSale.vo.OutStoreVo;
import com.xjrsoft.module.erpModel.caseErpStore.entity.CaseErpStoreReceipt;
import com.xjrsoft.module.erpModel.caseErpStore.service.ICaseErpStoreReceiptService;
import com.xjrsoft.module.erpModel.caseErpSupplier.vo.CaseErpSupplierPageVo;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.system.entity.DictionaryDetail;
import com.xjrsoft.module.system.service.IDictionarydetailService;
import io.reactivex.Completable;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售订单信息【case_erp_sale】 服务实现类
 * </p>
 *
 * @author hnyyzy
 * @since 2023-07-17
 */
@Service
@AllArgsConstructor
public class CaseErpSaleServiceImpl extends ServiceImpl<CaseErpSaleMapper, CaseErpSale> implements ICaseErpSaleService {

    private final ICaseErpSaleDetailService caseErpSaleDetailService;

    private final ICaseErpLogService caseErpLogService;

    private final RedisUtil redisUtil;

    private IDictionarydetailService dictionarydetailService;

    private ICaseErpStoreReceiptService caseErpStoreReceiptService;


    @Override
    public PageOutput<CaseErpSalePageVo> getPageList(CaseErpSalePageDto dto) {
        LambdaQueryWrapper<CaseErpSale> queryWrapper = Wrappers.lambdaQuery(CaseErpSale.class)
                .like(StrUtil.isNotBlank(dto.getTheme()), CaseErpSale::getTheme, dto.getTheme())
                .orderByDesc(CaseErpSale::getCreateDate);
        IPage<CaseErpSale> page = this.page(ConventPage.getPage(dto), queryWrapper);
        List<CaseErpSalePageVo> salePageVoList = BeanUtil.copyToList(page.getRecords(), CaseErpSalePageVo.class);
        List<CaseErpSaleDetail> saleDetailList = caseErpSaleDetailService.list();

        List<User> userList = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
        });
        for (CaseErpSalePageVo caseErpSalePageVo : salePageVoList) {
            StringBuilder detailStr = new StringBuilder();
            for (CaseErpSaleDetail saleDetail : saleDetailList) {
                if (ObjectUtil.equals(caseErpSalePageVo.getId(), saleDetail.getSaleId())) {
                    detailStr.append(StringPool.COMMA);
                    detailStr.append(saleDetail.getName());
                    detailStr.append(StringPool.COLON + StringPool.SPACE);
                    detailStr.append(String.format("%.0f", saleDetail.getCount()));
                }
            }
            if (detailStr.length() > 0) {
                detailStr.delete(0, 1);
            }
            caseErpSalePageVo.setSaleDetail(detailStr.toString());

            if (ObjectUtil.isNotEmpty(caseErpSalePageVo.getCreateUserId())) {
                User user = userList.stream().filter(x -> x.getId().equals(caseErpSalePageVo.getCreateUserId())).findFirst().orElse(new User());
                if (StrUtil.isNotBlank(user.getName())) {
                    caseErpSalePageVo.setCreateUserName(user.getName());
                }
            }
        }

        PageOutput<CaseErpSalePageVo> output = new PageOutput<>();
        output.setCurrentPage(dto.getLimit());
        output.setPageSize(dto.getSize());
        output.setTotal(saleDetailList.size());
        output.setList(salePageVoList);

        return output;
    }

    @Override
    public CaseErpSaleCheckInfoVo checkInfo(Long id) {
        CaseErpSale caseErpSale = this.getById(id);
        CaseErpSaleCheckInfoVo vo = BeanUtil.toBean(caseErpSale, CaseErpSaleCheckInfoVo.class);
        List<User> userList = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
        });
        List<DictionaryDetail> dictionaryDetailList = dictionarydetailService.list();
        if (ObjectUtil.isNotEmpty(vo.getRelatedProject())){
            DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getId().equals(vo.getRelatedProject())).findFirst().orElse(new DictionaryDetail());
            if (StrUtil.isNotBlank(dictionaryDetail.getName())) {
                vo.setRelatedProjectName(dictionaryDetail.getName());
            }
        }
        if (ObjectUtil.isNotEmpty(vo.getPayType())){
            DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getId().equals(vo.getPayType())).findFirst().orElse(new DictionaryDetail());
            if (StrUtil.isNotBlank(dictionaryDetail.getName())) {
                vo.setPayTypeName(dictionaryDetail.getName());
            }
        }
        if (ObjectUtil.isNotEmpty(vo.getCreateUserId())) {
            User user = userList.stream().filter(x -> x.getId().equals(vo.getCreateUserId())).findFirst().orElse(new User());
            if (StrUtil.isNotBlank(user.getName())) {
                vo.setCreateUserName(user.getName());
            }
        }
        if (ObjectUtil.isNotEmpty(vo.getModifyUserId())) {
            User user = userList.stream().filter(x -> x.getId().equals(vo.getModifyUserId())).findFirst().orElse(new User());
            if (StrUtil.isNotBlank(user.getName())) {
                vo.setModifyUserName(user.getName());
            }
        }
        //订单详情
        List<CaseErpSaleDetail> saledetailList = caseErpSaleDetailService.list(Wrappers.lambdaQuery(CaseErpSaleDetail.class).eq(CaseErpSaleDetail::getSaleId, id));
        vo.setCaseErpSaleDetailList(saledetailList);

        //开票
        vo.setInvoiceList(DataBuildUtil.buildInvoiceLogList(id));

        //拿销售的id去出入库单据表查询，有无关联数据，有的话就展示
        List<OutStoreVo> outStoreVos = new ArrayList<>();
        List<CaseErpStoreReceipt> list = caseErpStoreReceiptService.list(Wrappers.<CaseErpStoreReceipt>query().lambda().eq(CaseErpStoreReceipt::getRelationKeyId, id));
        if (CollectionUtil.isNotEmpty(list)){//真数据
            for (CaseErpStoreReceipt caseErpStoreReceipt : list) {
                OutStoreVo outStoreVo = new OutStoreVo();
                outStoreVo.setId(caseErpStoreReceipt.getId());
                outStoreVo.setCode(caseErpStoreReceipt.getCode());
                outStoreVo.setTheme(caseErpStoreReceipt.getName());
                outStoreVo.setDate(caseErpStoreReceipt.getCreateDate());
                outStoreVo.setName("客户一");
                outStoreVo.setPerson(caseErpStoreReceipt.getPersonNames());
                outStoreVo.setStore("仓库一");
                outStoreVos.add(outStoreVo);
            }
        }
        vo.setOutstoreList(outStoreVos);
        //生产
        vo.setProductList(DataBuildUtil.buildProductLogList(id));

        //收款
        vo.setCollectionList(DataBuildUtil.buildCollectionVoList(id));

        //操作记录
        List<CaseErpLog> logList = caseErpLogService.list(Wrappers.lambdaQuery(CaseErpLog.class).eq(CaseErpLog::getKeyId, id));
        for (CaseErpLog caseErpLog : logList) {
            if (ObjectUtil.isNotEmpty(caseErpLog.getCreateUserId())){
                 User user = userList.stream().filter(x -> x.getId().equals(caseErpLog.getCreateUserId())).findFirst().orElse(new User());
                 if (StrUtil.isNotBlank(user.getName())){
                     caseErpLog.setOperateUserAccount(user.getName());
                 }
            }
        }
        vo.setLogList(logList);

        return vo;
    }
}
